<?php
	error_reporting(E_ALL);

	class User extends CI_Controller
	{
		public $messagesPerPage;
		function __construct()
		{
			parent::__construct();
			preventCSRF();
			
			header("Content-Type: text/html; charset=utf-8");
			$this->load->model('user_model', 'user');
		}

		public function index()
		{
			die(":)");
		}

		#################################################################
		public function registration()
		{
			$data = new stdClass();
			if ($this->user->id()) redirect(''); 
			else
			{
				$cities = new stdClass();
				$cities = $this->user->getCities();

				$data->content = $this->load->view('user/reg', array('cities' => $cities), true);

				$data->title = 'Регистрация';
				// $data->addingJS = array('reg.js');

				$this->load->view('index', $data);
			}
		}

		public function saveReg()
		{
			$data = (object) $this->input->post(null, true);		

			// diepr($data);
			$error = $this->user->add($data);


			if (sizeof($error) && is_array($error))
			{
				$_SESSION['error'] = $error;
				unset($data->pPass);
				redirect('user/registration');
			} else if (is_int($error) && $error > 0)
			{
				$_SESSION['saveAbitur'] = 'На ваш email было отправлено письмо для подтверждения регистрации';
				redirect("/abiturient");
			}
		}

		public function sendMail($mail, $text,$title = 'Письмо от Системы Деканат')
		{	
			$email = 'guber321@mail.ru';

			$this->load->library('email');

			$this->email->from($email, 'Alex');

			$this->email->to($mail); 
			$this->email->subject('Тест Email');
			$this->email->message($text);	

			$this->email->send();

			diepr($this->email->print_debugger());
		}
		#################################################################
		public function viewProfile ($userId = 0)
		{		
			$userId = abs(@intval($userId));

			if (!$userId) $userId = $this->user->id();

			$data = new stdClass();
			$fdata->addingCSS = array('reg.css');

			$fdata->countries = $this->wed->getCountries();
			$fdata->cities = $this->wed->getCities();
			$fdata->data = $this->user->getUser($userId);
			
			if (!empty($fdata->data))
			{			
				if ($this->user->id()) $fdata->status = $this->user->checkFriendship($userId);
				$fdata->groupsIds = $this->knb->getUserGroupsIds($userId);
				
				if (is_arr($fdata->groupsIds))
					$fdata->roots = $this->knb->get(1, 1000, $fdata->groupsIds);

				$data->content = $this->load->view('user/viewUser', $fdata, true);
				$data->title = "Просмотр профиля";
			} else
			{
				$data->title = "Пользователь не найден";
				$_SESSION['error'] = "Пользователь не найден";
				header("Status: 404 Not Found");
			}

			$this->load->view('index', $data);
		}

		public function editProfile()
		{
			$this->user->refreshData();

			$data = new stdClass();
			if (!$this->user->id())
			{
				$_SESSION['error'] = 'Вы не авторизованы.';
			} else
			{
				$fdata->countries = $this->wed->getCountries();
				$fdata->cities = $this->wed->getCities();
				$fdata->data = $this->user->data();

				$data->content = $this->load->view('user/editUser', $fdata, true);
				$data->title = "Просмотр профиля";

				$data->addingCSS = array('reg.css');
				$data->addingJS = array('reg.js');
			}
			$this->load->view('index', $data);
		}

		public function saveUser()
		{
			$data = (object)$this->input->post();

			if (!empty($data->delAva))
			{
				$this->user->delAva();
				unset($data->delAva);
			}

			$error = $this->user->prepareUserData($data, true);

			if (is_object($error))
			{
				$data = $error;
				$this->user->update($data);
			}

			redirect('user/editProfile');
		}

		#################################################################
		public function activate($code = '')
		{
			$res = $this->user->activate($code);

			if ($res === true)
				$_SESSION['saveAbitur'] = 'Активация прошла успешно, воспользуйтесь формой входа.';
					else $_SESSION['error'] = 'Ошибка при активации.';

			redirect('/abiturient');
		}

		public function auth()
		{
			if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = base_url();
			$res = $this->user->auth();
			if ($res !== true)
			{ 
				$error[] = $res;
				$_SESSION['error']=$error;
			}
			header('Location: '.$_SERVER['HTTP_REFERER']);
		}

		public function recoveryReqest()
		{
			$email = $this->input->post('email');

			if (!$email || !isValidEmail($email))
			{
				$_SESSION['error'] = 'Ошибка восстановления пароля.';
				if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = base_url();
				header('Location: '.$_SERVER['HTTP_REFERER']);
			}

			$check = $this->user->check($email);

			if ($check)
			{
				$res = $this->user->recPass($email);
				if (!$res)
				{
					$_SESSION['error'] = 'Ошибка при отправке email.';
				}
				else
				{
					$_SESSION['error'] = 'На Ваш email отправлено письмо с потверждением запроса для смены пароля';
				}
				if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = base_url();
				header('Location: '.$_SERVER['HTTP_REFERER']);
			}
			else
			{
				$_SESSION['error'] = 'Данный email не зарегистрирован';
				redirect('');
			}
		}

		public function newpassAcceptSave()
		{
			$data = $this->input->post();
			$data = (object)$data;

			if (
				empty($data->pEmail) ||
				!isset($data->password) ||
				empty($data->pPassRecCode) ||
				(!isset($data->submitAccept) && !isset($data->submitCancel)) ||
				(strlen($data->password) != 32)
			)
			{
				$_SESSION['error'] = 'Неверный запрос на смену пароля';
				if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = base_url();
				header('Location: '.$_SERVER['HTTP_REFERER']);
				return true;
			}
			
			$pEmail = '';
			$res = $this->user->checkPassRecoveryCode($data->pPassRecCode, $pEmail);
			if (isset($data->submitAccept) && ($res === true) && ($pEmail == $data->pEmail))
			{
				$this->user->updatePass($pEmail, $data->password);
				$_SESSION['error'] = 'Пароль успешно изменен, воспользуйтесь формой входа';
				redirect('');
				return true;
			}
			else
			{
				if (is_string($res)) $_SESSION['error'] = $res;
					else $_SESSION['error'] = 'Ошибка, попробуйте запросить новую ссылку на восстановление пароля.';
				redirect('');
			}

		}

		public function newpassAccept($pPassRecCode = '')
		{
			$data = new stdClass();	
			$fdata = new stdClass();
			$fdata->pPassRecCode = $pPassRecCode;
			$pEmail = "";
			$res = $this->user->checkPassRecoveryCode($pPassRecCode, $pEmail);

			if ($res === true)
			{
				$fdata->pEmail = $pEmail;
				$data->content = $this->load->view('user/newpassAccept', $fdata, true);
				$data->title = 'Подтверждение восстановления пароля';
			}
			else
			{
				$_SESSION['error'] = $res;
				redirect('');
			}
			redirect(base_url());
		}

		public function logout()
		{
			$res = $this->user->logout();
		}


	}